import { useRequest } from 'ahooks';
import { Spin } from 'antd';

import { realTimeMonitoringControllerClusterRealtimeData } from '@/services/ess/realTimeMonitoring';

import { useEffect } from 'react';
import { useDeviceInfo, useIsFresh, useSelectedDeviceNode } from '../../SelectedDeviceNodeContext';
import { Info } from './Info';
import { Overview } from './Overview';

export const ClusterRealtimeInfo = () => {
  const deviceNode = useSelectedDeviceNode();
  const { setDeviceInfo } = useDeviceInfo();
  const { isRefesh, setIsRefesh } = useIsFresh();

  const { data, loading, refresh } = useRequest(
    () =>
      realTimeMonitoringControllerClusterRealtimeData({
        areaId: deviceNode?.areaId?.toString() ?? undefined,
        deviceCode: deviceNode?.deviceCode ?? undefined,
        deviceName: deviceNode?.deviceName ?? undefined,
        deviceType: deviceNode?.deviceType ?? undefined,
      }),
    {
      onSuccess: (responseData) => {
        setDeviceInfo({
          ts: responseData?.data?.clusterOverviewDto?.ts ?? undefined,
          onLine:
            responseData?.data?.clusterOverviewDto?.onlineState ||
            String(responseData?.data?.clusterOverviewDto?.onlineState) === '0'
              ? String(responseData?.data?.clusterOverviewDto?.onlineState)
              : undefined,
        });
        setIsRefesh(false); // 数据加载成功后重置 isRefesh
      },
      refreshDeps: [deviceNode], // 确保在 deviceNode 变化时重新运行 useRequest
    },
  );
  useEffect(() => {
    if (isRefesh) {
      refresh();
    }
  }, [deviceNode, refresh]);

  return (
    <Spin spinning={loading}>
      <Info data={data?.data} />
      <div style={{ marginLeft: 60 }}>
        <Overview />
      </div>
    </Spin>
  );
};
